<template>
    <div class="user-views">
        <el-card class="notice-card">
            <template #header>
                <div class="card-header">
                    <div class="header-left">
                        <el-icon class="header-icon"><Bell /></el-icon>
                        <span class="header-title">系统公告</span>
                    </div>
                    <div class="header-right">
                        <span class="total-text">共 {{ total }} 条公告</span>
                    </div>
                </div>
            </template>

            <!-- 公告列表 -->
            <div class="notice-list">
                <div v-for="(item, index) in noticeList" :key="index" class="notice-item">
                    <div class="notice-main">
                        <div class="notice-header">
                            <div class="notice-image-container">
                                <el-image
                                    class="notice-image"
                                    :src="fullUrl(item.image)"
                                    :preview-src-list="[fullUrl(item.image)]"
                                    fit="cover"
                                    hide-on-click-modal
                                    preview-teleported
                                >
                                    <template #error>
                                        <div class="image-error">
                                            <el-icon><Picture /></el-icon>
                                        </div>
                                    </template>
                                </el-image>
                            </div>
                            <div class="notice-content">
                                <h3 class="notice-title">{{ extractTitle(item.editor) }}</h3>
                                <div class="notice-meta">
                                    <span class="notice-time">{{ timeFormat(item.create_time) }}</span>
                                    <el-tag :type="item.status === 1 ? 'success' : 'info'" size="small">
                                        {{ item.status === 1 ? '启用' : '禁用' }}
                                    </el-tag>
                                </div>
                                <div class="notice-preview">
                                    {{ extractPreview(item.editor) }}
                                </div>
                                <div class="notice-actions">
                                    <el-button type="primary" size="small" @click="viewDetail(item)">
                                        <el-icon><View /></el-icon>
                                        查看详情
                                    </el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 分页 -->
            <div class="notice-footer-pagination" v-if="total > 0">
                <el-pagination
                    v-model:current-page="queryParams.page"
                    v-model:page-size="queryParams.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>

            <!-- 空状态 -->
            <el-empty v-if="noticeList.length === 0 && !loading" description="暂无公告" :image-size="200" />

            <!-- 加载状态 -->
            <div v-if="loading" class="loading-container">
                <el-skeleton :rows="5" animated />
            </div>
        </el-card>

        <!-- 公告详情对话框 -->
        <el-dialog
            v-model="showDetailDialog"
            :title="currentNotice ? extractTitle(currentNotice.editor) : '公告详情'"
            width="90%"
            :fullscreen="isFullscreen"
            :before-close="handleCloseDialog"
        >
            <div v-if="currentNotice" class="notice-detail">
                <!-- 公告头部信息 -->
                <div class="detail-header">
                    <div class="detail-meta">
                        <span class="detail-time">发布时间：{{ timeFormat(currentNotice.create_time) }}</span>
                        <el-tag :type="currentNotice.status === 1 ? 'success' : 'info'" size="small">
                            {{ currentNotice.status === 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </div>
                    <div class="detail-actions">
                        <el-button link type="primary" @click="toggleFullscreen">
                            <el-icon>
                                <FullScreen v-if="!isFullscreen" />
                                <Close v-else />
                            </el-icon>
                            {{ isFullscreen ? '退出全屏' : '全屏查看' }}
                        </el-button>
                    </div>
                </div>

                <!-- 公告封面图 -->
                <div class="detail-cover" v-if="currentNotice.image">
                    <el-image
                        class="cover-image"
                        :src="fullUrl(currentNotice.image)"
                        :preview-src-list="[fullUrl(currentNotice.image)]"
                        fit="contain"
                        hide-on-click-modal
                        preview-teleported
                    />
                </div>

                <!-- 富文本内容 -->
                <div class="detail-content">
                    <div class="rich-content" v-html="formatRichContent(currentNotice.editor)"></div>
                </div>
            </div>

            <template #footer>
                <el-button @click="showDetailDialog = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { notice } from '/@/api/frontend/user/index'
import { timeFormat, fullUrl } from '/@/utils/common'
import { ElMessage } from 'element-plus'
import { Bell, View, Picture, FullScreen, Close } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const total = ref(0)
const noticeList = ref<any[]>([])
const showDetailDialog = ref(false)
const isFullscreen = ref(false)
const currentNotice = ref<any>(null)

const queryParams = reactive({
    page: 1,
    pageSize: 10,
})

// 从富文本中提取标题（取第一个段落或前50个字符）
const extractTitle = (editor: string) => {
    if (!editor) return '无标题'

    // 移除HTML标签
    const text = editor.replace(/<[^>]*>/g, '').trim()

    // 取第一个段落或前50个字符
    const firstParagraph = text.split('\n')[0]
    if (firstParagraph && firstParagraph.length > 0) {
        return firstParagraph.length > 50 ? firstParagraph.substring(0, 50) + '...' : firstParagraph
    }

    return text.length > 50 ? text.substring(0, 50) + '...' : text || '无标题'
}

// 从富文本中提取预览内容
const extractPreview = (editor: string) => {
    if (!editor) return '无内容'

    // 移除HTML标签
    const text = editor.replace(/<[^>]*>/g, '').trim()

    // 取前100个字符作为预览
    return text.length > 100 ? text.substring(0, 100) + '...' : text
}

// 格式化富文本内容，确保样式正确
const formatRichContent = (editor: string) => {
    if (!editor) return ''

    // 这里可以添加一些样式处理
    return editor
}

// 查看详情
const viewDetail = async (item: any) => {
    try {
        currentNotice.value = item
        showDetailDialog.value = true
        isFullscreen.value = false
    } catch (error) {
        console.error('获取公告详情失败:', error)
        ElMessage.error('获取公告详情失败')
    }
}

// 切换全屏
const toggleFullscreen = () => {
    isFullscreen.value = !isFullscreen.value
}

// 关闭对话框
const handleCloseDialog = () => {
    showDetailDialog.value = false
    isFullscreen.value = false
    currentNotice.value = null
}

// 获取公告列表
const fetchNotice = async () => {
    try {
        loading.value = true
        const response = await notice(queryParams.page, queryParams.pageSize)

        if (response && response.code === 1 && response.data) {
            noticeList.value = response.data.list || []
            total.value = response.data.total || 0
        } else {
            noticeList.value = []
            total.value = 0
        }
    } catch (error) {
        console.error('获取公告失败:', error)
        ElMessage.error('获取公告失败')
        noticeList.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

// 分页大小改变
const handleSizeChange = (newSize: number) => {
    queryParams.pageSize = newSize
    queryParams.page = 1
    fetchNotice()
}

// 当前页改变
const handleCurrentChange = (newPage: number) => {
    queryParams.page = newPage
    fetchNotice()
}

// 初始化
onMounted(() => {
    fetchNotice()
})
</script>

<style scoped lang="scss">
.notice-card {
    margin: 20px;

    :deep(.el-card__header) {
        padding: 16px 20px;
        border-bottom: 1px solid var(--el-border-color-light);
    }
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-icon {
    font-size: 18px;
    color: var(--el-color-primary);
}

.header-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
}

.header-right {
    .total-text {
        color: var(--el-text-color-secondary);
        font-size: 14px;
    }
}

.notice-list {
    padding: 0;
}

.notice-item {
    padding: 20px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    transition: all 0.3s ease;

    &:last-child {
        border-bottom: none;
    }

    &:hover {
        background-color: var(--el-fill-color-light);
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
}

.notice-main {
    max-width: 100%;
}

.notice-header {
    display: flex;
    gap: 16px;
    align-items: flex-start;
}

.notice-image-container {
    flex-shrink: 0;
    width: 120px;
    height: 80px;
}

.notice-image {
    width: 100%;
    height: 100%;
    border-radius: 8px;
    cursor: pointer;
    border: 1px solid var(--el-border-color-light);
    object-fit: cover;
}

.image-error {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--el-fill-color-light);
    border-radius: 8px;
    color: var(--el-text-color-placeholder);

    .el-icon {
        font-size: 24px;
    }
}

.notice-content {
    flex: 1;
    min-width: 0;
}

.notice-title {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    line-height: 1.4;
}

.notice-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
}

.notice-time {
    color: var(--el-text-color-secondary);
    font-size: 13px;
}

.notice-preview {
    color: var(--el-text-color-regular);
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 12px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.notice-actions {
    display: flex;
    gap: 8px;
}

.notice-footer-pagination {
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-light);
    display: flex;
    justify-content: center;
}

.loading-container {
    padding: 40px 0;
}

:deep(.el-pagination) {
    justify-content: center;
}

/* 详情对话框样式 */
.notice-detail {
    max-height: 70vh;
    overflow-y: auto;
}

.detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--el-border-color-light);
}

.detail-meta {
    display: flex;
    align-items: center;
    gap: 12px;
}

.detail-time {
    color: var(--el-text-color-secondary);
    font-size: 14px;
}

.detail-actions {
    display: flex;
    gap: 8px;
}

.detail-cover {
    margin-bottom: 20px;
    text-align: center;
}

.cover-image {
    max-width: 100%;
    max-height: 300px;
    border-radius: 8px;
    cursor: pointer;
}

.detail-content {
    line-height: 1.6;

    :deep(.rich-content) {
        // 富文本内容样式
        img {
            max-width: 100%;
            height: auto;
            border-radius: 4px;
        }

        a {
            color: var(--el-color-primary);
            text-decoration: none;
        }

        h1,
        h2,
        h3,
        h4,
        h5,
        h6 {
            margin: 16px 0 8px 0;
            color: var(--el-text-color-primary);
        }

        p {
            margin: 8px 0;
        }

        // 评论区域样式
        .comment-section {
            background: var(--el-fill-color-light);
            padding: 16px;
            border-radius: 8px;
            margin: 16px 0;
        }
    }
}

// 全屏模式
:deep(.el-dialog__wrapper) {
    &.is-fullscreen {
        .el-dialog {
            margin: 0;
            width: 100%;
            height: 100%;
            max-height: 100%;

            .el-dialog__body {
                height: calc(100% - 55px - 53px);
                padding: 0;

                .notice-detail {
                    max-height: 100%;
                    height: 100%;
                    padding: 20px;
                }
            }
        }
    }
}

@media (max-width: 768px) {
    .notice-card {
        margin: 10px;
    }

    .notice-header {
        flex-direction: column;
        gap: 12px;
    }

    .notice-image-container {
        width: 100%;
        height: 160px;
    }

    .detail-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }

    .detail-actions {
        width: 100%;
        justify-content: flex-end;
    }

    :deep(.el-dialog) {
        width: 95% !important;
        margin: 20px auto;
    }
}
</style>
